package com.luoguijia.disk.login.service.impl;

import com.luoguijia.disk.login.repository.LoginDao;
import com.luoguijia.disk.login.service.LoginService;
import com.luoguijia.disk.login.service.PasswordResetService;
import com.luoguijia.disk.mybatis.entity.PtUserEntity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Service
public class PasswordResetServiceImpl implements PasswordResetService {

    @Resource
    private LoginService loginService;

    @Resource
    private LoginDao loginDao;

    @Resource
    private PasswordEncoder passwordEncoder;

    @Override
    public Map<String, Object> sendResetPasswordCode(String email) {
        Map<String, Object> result = new HashMap<>();

        // 检查邮箱是否存在
        PtUserEntity user = loginDao.queryUserInfoByEmail(email);
        if (user == null) {
            result.put("success", false);
            result.put("message", "该邮箱未注册");
            return result;
        }

        // 发送验证码
        String code = loginService.sendVerificationCodeByEmail(email);
        if (code != null) {
            result.put("success", true);
            result.put("message", "验证码已发送，请查收邮件");
        } else {
            result.put("success", false);
            result.put("message", "验证码发送失败，请稍后重试");
        }

        return result;
    }

    @Override
    @Transactional
    public Map<String, Object> resetPassword(String email, String code, String newPassword) {
        Map<String, Object> result = new HashMap<>();

        // 验证邮箱是否存在
        PtUserEntity user = loginDao.queryUserInfoByEmail(email);
        if (user == null) {
            result.put("success", false);
            result.put("message", "该邮箱未注册");
            return result;
        }

        // 验证验证码
        boolean codeValid = loginService.verifyEmailCode(email, code);
        if (!codeValid) {
            result.put("success", false);
            result.put("message", "验证码无效或已过期");
            return result;
        }

        // 加密新密码并更新
        String encodedPassword = passwordEncoder.encode(newPassword);
        loginDao.updatePassword(user.getUserUuid(), encodedPassword);

        result.put("success", true);
        result.put("message", "密码重置成功");
        return result;
    }
}